<!--
 * @Description: radio单选
 * @Author: huacong
 * @Date: 2020-11-11 13:13:04
 * @LastEditTime: 2020-11-16 22:12:04
 * @LastEditors: huacong
-->
<template lang="pug">
  el-radio-group.mr5.w(v-model="currentValue" placeholder="请选择" v-on="$listeners" v-bind="formFieldProps")
    radio-child(v-for="item in opts" :type="type" :key="item[prop.value]" :label="item[prop.value]")
      | {{item[prop.label]}}
</template>
<script>
import Vue from 'vue'
import omit from 'lodash/omit'
import { dictMixin } from '@/mixins'

Vue.component('radioChild', {
  props: {
    type: { type: Number, default: 0 },
    label: { type: String, default: '' }
  },
  render (h) {
    const tag = ['el-radio', 'el-radio-button'][this.type]
    return h(tag, {
      attrs: {
        label: this.label
      }
    }, this.$slots.default)
  }
})

export default {
  name: 'IRadio',
  mixins: [dictMixin],
  props: {
    value: {
      type: [String, Number, Array],
      default: ''
    },
    type: {
      type: Number,
      default: 0
    },
    dictKey: {
      type: String,
      default: ''
    },
    options: {
      type: Array,
      default: () => ([])
    },
    props: {
      type: Object,
      default: () => ({})
    },
    dictParams: {
      type: Object,
      default: () => ({})
    }
  },
  computed: {
    prop () {
      const { props } = this
      return {
        label: props?.label || 'name',
        value: props?.value || 'id'
      }
    },
    formFieldProps () {
      return omit(this.$attrs, ['props', 'options', 'dictParams'])
    },
    currentValue: {
      // 通过计算属性，对.sync进行转换，外部也可以直接使用initId.sync
      get () {
        return this.value
      },
      set (val) {
        this.$emit('input', val)
        this.$emit('valChange', val)
      }
    },
    // 选项
    opts () {
      const { dictKey, options } = this
      return dictKey ? (this.dict[dictKey] || []) : options
    }
  },
  watch: {
    // 获取dict列表
    dictKey: {
      handler (val) {
        if (val) {
          const { dictKey, dictParams } = this
          if (!this.dict[dictKey]) {
            this.getDict({ fieldName: dictKey, ...dictParams })
          }
        }
      },
      immediate: true
    }
  }
}
</script>
